﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Acid.Math
{
    public class Triangle
    {
        public Vector3 vert0;
        public Vector3 vert1;
        public Vector3 vert2;

        public Triangle(Vector3 vert0, Vector3 vert1, Vector3 vert2)
        {
            this.vert0 = vert0;
            this.vert1 = vert1;
            this.vert2 = vert2;
        }

        public bool Intersect(Ray ray)
        {
            float t; return Triangle.Intersect(ray, this.vert0, this.vert1, this.vert2, out t);
        }

        public static bool Intersect(Ray r, Vector3 vert0, Vector3 vert1, Vector3 vert2, out float t)
        {
            t = 0;

            Vector3 edge1 = vert1 - vert0;
            Vector3 edge2 = vert2 - vert0;
            Vector3 tvec, pvec, qvec;
            float det, inv_det;

            pvec = Vector3.Cross(r.Direction, edge2);

            det  = Vector3.Dot(edge1, pvec);

            if (det > -0.00001f)
                return false;

            inv_det = 1.0f / det;

            tvec = r.Position - vert0;

            float u = Vector3.Dot(tvec, pvec) * inv_det;
            if (u < -0.001f || u > 1.001f)
                return false;

            qvec = Vector3.Cross(tvec, edge1);

            float v = Vector3.Dot(r.Direction, qvec) * inv_det;
            if (v < -0.001f || u + v > 1.001f)
                return false;

            t = Vector3.Dot(edge2, qvec) * inv_det;

            if (t <= 0)
            {
                return false;
            }
            return true;
        }

    }
}
